package com.shg.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.shg.bean.BookType;
import com.shg.bean.TypeSearch;
import com.shg.service.TypeSearchService;

@Service
public class TypeSearchServiceBean extends BasiceDaoImpl<TypeSearch> implements TypeSearchService {

		private Map<String, String> search=new LinkedHashMap<String, String>();
		
		private String key;
		/**
		 * 添加索引
		 * 1、删除数据库里面的索引
		 * 2、重新添加索引
		 */
		public void addSearch() throws Exception{
			//删除原有数据
			String sql="delete from TypeSearch";
			sessionFactory.getCurrentSession().createQuery(sql).executeUpdate();
			//构建新的书籍类型索引
			sql="from BookType";
			List<BookType> bookTypes=sessionFactory.getCurrentSession().createQuery(sql).list();
			for(BookType type:bookTypes){
				this.key=type.getId();
				search.put(this.key, "");
				List<String> list=new ArrayList<String>();
				list.add(this.key);
				makeSearch(list);
				//构建实体
				TypeSearch typeSearch=new TypeSearch();
				typeSearch.setName(type.getName());
				typeSearch.setChild(search.get(this.key));
				typeSearch.setBookType(type);
				sessionFactory.getCurrentSession().save(typeSearch);
			}
		}
		/**
		 * 组织索引
		 * @param ids 父类ID数组
		 */
		private void makeSearch(List<String>ids){
			String idList  = ids.toString().replace("[","'").replace("]", "'").replace(",", "','").replace(" ", "");
			String values=search.get(this.key).trim().length()>0 ? search.get(this.key)+","+idList : idList;
			search.put(this.key, values);
			
			String sql="select id from BookType where parent_id in("+idList+")";
			List<String> childs = sessionFactory.getCurrentSession().createSQLQuery(sql).list();
			if(childs.size()>0)
				makeSearch(childs);
		}
}
